package www.dianbaozu.com.extension

import com.netease.nim.uikit.api.NIMHelper
import com.netease.nimlib.sdk.RequestCallback
import com.netease.nimlib.sdk.auth.LoginInfo
import com.orhanobut.logger.Logger
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import www.wen.com.common.lib.helper.loading.KeyHelper
import www.wen.com.common.lib.helper.loading.KeyHelper.MMKV_ACCESS_TOKEN
import www.wen.com.common.lib.helper.loading.KeyHelper.MMKV_ACCID
import www.wen.com.common.lib.helper.loading.KeyHelper.MMKV_ACC_TOKEN
import www.wen.com.common.lib.util.SpUtil

/**
 * @author WEN
 * @Description:
 * @date 2021/1/29 10:03
 */

//判断用户是否已经登录
@Throws(Exception::class)
fun Any.isLogged(scope: CoroutineScope, logging: (() -> Unit)? = null, logged: (() -> Unit)? = null, logout: (() -> Unit)? = null): Boolean {
    return if (SpUtil.decodeString(MMKV_ACCESS_TOKEN)!!.isNotBlank()) {
        if (System.currentTimeMillis() / 1000 - SpUtil.decodeLong(KeyHelper.MMKV_LOGIN_TIME, 0)!! < SpUtil.decodeLong(KeyHelper.MMKV_EXPIRES_IN)!!) {
            logging?.invoke()
            scope.launch(context = Dispatchers.IO) {
                Logger.i("云信登录开始 accId = ${SpUtil.decodeString(MMKV_ACCID)},token = ${SpUtil.decodeString(MMKV_ACC_TOKEN)}")
                NIMHelper.login(
                        SpUtil.decodeString(MMKV_ACCID)!!,
                        SpUtil.decodeString(MMKV_ACC_TOKEN)!!,
                        object : RequestCallback<LoginInfo?> {
                            override fun onSuccess(param: LoginInfo?) {
                                NIMHelper.loginSuccessInit(param?.account)
                                logged?.invoke()
                                Logger.i("云信登录成功")
                            }

                            override fun onFailed(code: Int) {
                                Logger.i("云信登录失败-> 错误代码:$code")
                                logout?.invoke()
                            }

                            override fun onException(exception: Throwable?) {
                                Logger.i("云信登录失败-> 错误代")
                                logout?.invoke()

                            }

                        })
            }
        } else {
            logout?.invoke()
        }
        true
    } else {
        logout?.invoke()
        false
    }
}